package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.exception.BaseException;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.mapperResult.DailyNewUsers;
import com.sky.mapperResult.DailyOrderCount;
import com.sky.mapperResult.DailyTurnover;
import com.sky.mapperResult.TotalUser;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl  implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 根据时间区间统计营业额
     * @param begin
     * @param end
     * @return
     *//*
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //1.完成dateList
        List<LocalDate> dateList = new ArrayList<LocalDate>();
        while (!begin.isAfter(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        //2.完成 turnoverList
        ArrayList<Double> turnoverList = new ArrayList<>();
        //查询 dateList 里的每个日期的营业额（已完成订单金额总和）
        for (LocalDate date : dateList) {
            //对齐时间格式
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);

            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        //3.返回封装好的数据TurnoverReportVO
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }*/

    /**
     * 根据时间区间统计营业额
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //1.完成 dateList
        List<LocalDate> dateList = getDatelist(begin, end);
        //2.完成 turnoverList
        LocalDateTime beginTime = LocalDateTime.of(dateList.get(0), LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(dateList.get(dateList.size() - 1), LocalTime.MAX);

        Map<String, Object> map = new HashMap<>();
        map.put("status", Orders.COMPLETED);
        map.put("begin", beginTime);
        map.put("end", endTime);

        // 获取按日期分组的营业额数据
        List<DailyTurnover> turnoverSource= orderMapper.sumByDateRange(map);

        // 使用通用方法填充营业额数据
        List<Double> turnoverList = convertToOrderedList(turnoverSource,
                DailyTurnover::getOrderDate,
                DailyTurnover::getDailyAmount,
                dateList,
                0.0);
        //3.返回封装好的数据TurnoverReportVO
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 得到总用户量和新增用户数
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //1. 完成 dateList
        List<LocalDate> dateList = getDatelist(begin, end);
        //2. 完成 newUserList
        LocalDateTime beginTime = LocalDateTime.of(dateList.get(0), LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,  LocalTime.of(23, 59, 59));

        Map<String, Object> map = new HashMap<>();
        map.put("begin", beginTime);
        map.put("end", endTime);
        // 获取按日期分组的新增用户数数据
        List<DailyNewUsers> newUsersSource = userMapper.countNewUsersByDateRange(map);
        // 使用通用方法填充数据
        List<Integer> newUserList = convertToOrderedList(newUsersSource,
                DailyNewUsers::getUserDate,
                DailyNewUsers::getDailyNewUsers,
                dateList,
                0);
        //3. 完成 totalUserList
        // 获取截止某日的总用户数, endTime 使用 LocalTime.MAX ,选择7日时，这里sql会返回8条记录，因为 endTime 精度太高,某些数据库会将其四舍五入到第二天，从而导致多返回一条记录。
        List<TotalUser> totalUserSource = userMapper.countTotalUsersByDateRange(map);
        // 使用通用方法填充数据
        List<Integer> totalUserList = convertToOrderedList(totalUserSource,
                TotalUser::getUserDate,
                TotalUser::getTotalUsers,
                dateList,
                0);
        //4.返回封装好的数据TurnoverReportVO
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * 根据时间区间统计订单数量
     * @param begin 开始日期
     * @param end 结束日期
     * @return OrderStatisticsVO
     */
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //1. 完成 dateList
        List<LocalDate> dateList = getDatelist(begin, end);
        //2. 完成 orderCountList
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        Map<String, Object> map = new HashMap<>();
        map.put("begin", beginTime);
        map.put("end", endTime);
        // 获取按日期分组的订单数量
        List<DailyOrderCount> orderCountSource = orderMapper.countOrderByDateRange(map);
        // 使用通用方法填充数据
        List<Integer> orderCountList = convertToOrderedList(orderCountSource,
                DailyOrderCount::getOrderDate,
                DailyOrderCount::getDailyOrderCount,
                dateList,
                0);
        //3. 完成 validOrderCountList
        map.put("status", Orders.COMPLETED);
        // 获取按日期分组的订单数量
        List<DailyOrderCount> validOrderCountSource = orderMapper.countOrderByDateRange(map);
        // 使用通用方法填充数据
        List<Integer> validOrderCountList = convertToOrderedList(validOrderCountSource,
                DailyOrderCount::getOrderDate,
                DailyOrderCount::getDailyOrderCount,
                dateList,
                0);
        //4. 时间区间内的总订单数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //5. 时间区间内的总有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //6. 订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        //7. 返回封装好的数据TurnoverReportVO
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量排名统计
     * @param begin 开始日期
     * @param end 结束日期
     * @return SalesTop10ReportVO
     */
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        //1. 完成 dateList
        List<LocalDate> dateList = getDatelist(begin, end);
        //2. 完成 goodsSalesDTOList
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        Map<String, Object> map = new HashMap<>();
        map.put("begin", beginTime);
        map.put("end", endTime);
        map.put("status", Orders.COMPLETED);
        // 获取按日期查询的top10
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(map);
        //得到 nameList numberList
        List<String> names = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");
        List<Integer> numbers = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");

        //3. 返回封装好的数据 SalesTop10ReportVO
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出近30天的运营数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1. 查询概览运营数据，提供给Excel模板文件
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        //2. 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template//运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + begin + "至" + end);
            //第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
            //准备明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //3. 通过输出流将文件下载到客户端浏览器中
    }

    /**
     * 得到begin-end的日期列表
     * @param begin
     * @param end
     * @return
     */
    private static List<LocalDate> getDatelist(LocalDate begin, LocalDate end) {
        //1.完成 dateList
        List<LocalDate> dateList = new ArrayList<>();
        //begin end合法性判断
        if (begin == null || end == null || begin.isAfter(end)) {
            throw new BaseException("begin or end is error!");
        }
        while (!begin.isAfter(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        return dateList;
    }

    /**
     * 提取value封装为list
     * @param sourceList
     * @param dateExtractor
     * @param valueExtractor
     * @param dateList
     * @return
     * @param <T>
     */
    public static <T> List<Double> convertToOrderedList(List<T> sourceList,
                                                        Function<T, LocalDate> dateExtractor,
                                                        Function<T, Double> valueExtractor,
                                                        List<LocalDate> dateList) {
        // 将查询结果转为日期到对应数值的映射，方便查找
        Map<LocalDate, Double> dateToValue = new HashMap<>();
        for (T item : sourceList) {
            LocalDate date = dateExtractor.apply(item);
            Double value = valueExtractor.apply(item);
            dateToValue.put(date, value);
        }

        // 按照日期列表顺序填充数值数据
        List<Double> resultList = new ArrayList<>();
        for (LocalDate date : dateList) {
            Double amount = dateToValue.getOrDefault(date, 0.0);
            resultList.add(amount);
        }
        return resultList;
    }

    /**
     * 将源列表按日期顺序转换为数值列表（支持Integer或Double）
     *
     * @param sourceList 源数据列表
     * @param dateExtractor 从源数据提取日期的方法
     * @param valueExtractor 从源数据提取数值的方法
     * @param dateList 目标日期顺序列表
     * @param defaultValue 默认填充值（需与T一致）
     * @return 按日期顺序排列的数值列表
     */
    public static <T, R extends Number> List<R> convertToOrderedList(
            List<T> sourceList,
            Function<T, LocalDate> dateExtractor,
            Function<T, R> valueExtractor,
            List<LocalDate> dateList,
            R defaultValue) {

        // 将查询结果转为日期到对应数值的映射
        Map<LocalDate, R> dateToValue = new HashMap<>();
        for (T item : sourceList) {
            LocalDate date = dateExtractor.apply(item);
            R value = valueExtractor.apply(item);
            dateToValue.put(date, value);
        }

        // 按照日期列表顺序填充数值数据
        List<R> resultList = new ArrayList<>();
        for (LocalDate date : dateList) {
            R value = dateToValue.getOrDefault(date, defaultValue);
            resultList.add(value);
        }
        return resultList;
    }
}
